from rest_framework import serializers
from .models import Order, OrderItem
from products.serializers import ProductSerializer
from products.models import Product
from warehouse.models import Inventory, InventoryRecord, Warehouse
from django.db import transaction
from django.utils import timezone
from django.db.models import F
from decimal import Decimal

class OrderItemSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.name', read_only=True)
    unit = serializers.CharField(source='product.unit', read_only=True)
    product_id = serializers.IntegerField(write_only=True)
    warehouse_id = serializers.IntegerField(write_only=True, required=False)

    class Meta:
        model = OrderItem
        fields = ['id', 'product_id', 'product_name', 'quantity', 'unit', 'unit_price', 'total_price', 'warehouse_id']
        read_only_fields = ['id', 'total_price', 'product_name', 'unit']

class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)
    customer_name = serializers.CharField(source='customer.username', read_only=True)
    salesman_name = serializers.CharField(source='salesman.username', read_only=True, allow_null=True)
    items_data = serializers.ListField(child=serializers.DictField(), write_only=True)
    address = serializers.CharField(required=True)
    phone = serializers.CharField(required=True)

    class Meta:
        model = Order
        fields = ['id', 'order_number', 'customer', 'customer_name', 'salesman', 'salesman_name', 
                 'total_amount', 'status', 'payment_method', 'payment_time', 'address', 'phone', 
                 'remark', 'created_at', 'updated_at', 'items', 'items_data']
        read_only_fields = ['id', 'order_number', 'total_amount', 'created_at', 'updated_at', 'salesman']

    @transaction.atomic
    def create(self, validated_data):
        items_data = validated_data.pop('items_data', [])
        
        # 设置订单状态为已付款
        validated_data['status'] = 'paid'
        # 设置支付时间为当前时间
        validated_data['payment_time'] = timezone.now()
        # 设置默认支付方式（如果需要）
        if 'payment_method' not in validated_data or not validated_data['payment_method']:
            validated_data['payment_method'] = '在线支付'
        
        order = Order.objects.create(**validated_data)
        
        total_amount = Decimal('0')
        for item_data in items_data:
            product_id = item_data.pop('product_id')
            quantity = Decimal(str(item_data.get('quantity', 1)))
            
            # 确保 unit_price 是 Decimal 类型
            unit_price_str = item_data.get('unit_price')
            if unit_price_str is None:
                # 如果前端没有提供 unit_price，从产品中获取
                product = Product.objects.get(id=product_id)
                unit_price = product.price
            else:
                # 确保 unit_price 是 Decimal 类型
                try:
                    unit_price = Decimal(str(unit_price_str))
                except (TypeError, ValueError):
                    raise serializers.ValidationError(f'无效的单价: {unit_price_str}')
            
            # 自动选择仓库（如果未提供）
            warehouse_id = item_data.pop('warehouse_id', None)
            if not warehouse_id:
                # 查找有足够库存的仓库，优先选择库存量最多的
                inventory = Inventory.objects.filter(
                    product_id=product_id,
                    current_stock__gte=quantity,
                    warehouse__status='active'  # 只选择启用状态的仓库
                ).order_by('-current_stock').first()
                
                if inventory:
                    warehouse_id = inventory.warehouse_id
                else:
                    # 如果没有足够库存的仓库，选择库存最多的仓库
                    inventory = Inventory.objects.filter(
                        product_id=product_id,
                        warehouse__status='active'
                    ).order_by('-current_stock').first()
                    
                    if inventory:
                        warehouse_id = inventory.warehouse_id
                    else:
                        # 如果没有任何库存记录，选择第一个可用的仓库
                        warehouse = Warehouse.objects.filter(status='active').first()
                        if warehouse:
                            warehouse_id = warehouse.id
                        else:
                            raise serializers.ValidationError('没有可用的仓库')
            
            # 验证库存是否足够（但不减少库存，只是验证）
            try:
                inventory = Inventory.objects.get(product_id=product_id, warehouse_id=warehouse_id)
                if inventory.current_stock < quantity:
                    raise serializers.ValidationError(f'商品ID {product_id} 在仓库ID {warehouse_id} 的库存不足')
            except Inventory.DoesNotExist:
                # 如果不存在库存记录，创建一个初始库存为0的记录
                product = Product.objects.get(id=product_id)
                inventory = Inventory.objects.create(
                    product_id=product_id,
                    warehouse_id=warehouse_id,
                    current_stock=0,
                    min_stock=product.min_stock,
                    status='normal'
                )
                raise serializers.ValidationError(f'商品ID {product_id} 在仓库ID {warehouse_id} 的库存不足')
            
            # 创建订单项
            order_item = OrderItem.objects.create(
                order=order,
                product_id=product_id,
                warehouse_id=warehouse_id,
                quantity=quantity,
                unit_price=unit_price,
                total_price=quantity * unit_price
            )
            
            # 更新总金额
            total_amount += order_item.total_price
            
            # 注意：不再在这里减少库存，而是在配送状态变为"正在配送"时减少
        
        # 更新订单总金额
        order.total_amount = total_amount
        order.save()
        
        # 创建配送任务
        try:
            from delivery.models import DeliveryTask
            import uuid
            delivery_number = f'DT{timezone.now().strftime("%Y%m%d")}{str(uuid.uuid4().int)[:6]}'
            
            # 创建配送任务
            delivery_task = DeliveryTask.objects.create(
                delivery_number=delivery_number,
                sales_order=order,
                status='pending',
                priority='medium',
                estimated_delivery_time=timezone.now() + timezone.timedelta(hours=2),
                note=f'订单 {order.order_number} 的配送任务'
            )
            
            # 自动分配配送员
            from orders.views import auto_assign_deliveryman_helper
            auto_assign_deliveryman_helper(delivery_task, order.customer)
            
        except Exception as e:
            # 记录错误但不影响订单创建
            print(f"创建配送任务时出错: {str(e)}")
        
        return order